package com.uduemc.jcms.backend.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.uduemc.jcms.backend.BackendModule;
import com.uduemc.jcms.backend.dto.RepertoryOutsidelinkSave;
import com.uduemc.jcms.backend.dto.RepertoryUpdate;
import com.uduemc.jcms.backend.service.IBJcmsRepertoryLabelService;
import com.uduemc.jcms.backend.service.IBJcmsRepertoryService;
import com.uduemc.jcms.common.utils.JsonResult;
import com.uduemc.jcms.common.utils.PageDataUtil;
import com.uduemc.jcms.component.RepertoryUtil;
import com.uduemc.jcms.generate.entity.JcmsRepertory;
import com.uduemc.jcms.generate.entity.JcmsRepertoryLabel;

import cn.hutool.core.util.StrUtil;

@Controller
@RequestMapping(BackendModule.BaseRequest + "/repertory")
public class BRepertoryController {

	@Autowired
	IBJcmsRepertoryLabelService bjcmsRepertoryLabelServiceImpl;

	@Autowired
	IBJcmsRepertoryService bjcmsRepertoryServiceImpl;

	@Autowired
	ObjectMapper objectMapper;

	@Autowired
	RepertoryUtil repertoryUtil;

	@GetMapping(value = "/index.html")
	public String index(HttpServletRequest request) throws JsonProcessingException {
		List<JcmsRepertoryLabel> list = bjcmsRepertoryLabelServiceImpl.list();
		request.setAttribute("labeles", objectMapper.writeValueAsString(PageDataUtil.easyuiResult(list)));
		return "backend/repertory/index";
	}

	@GetMapping(value = "/index-infos.html")
	@ResponseBody
	public JsonResult indexInfos(@RequestParam(value = "filename", defaultValue = "") String originalFilename,
			@RequestParam(value = "label_id") List<Long> labelids, @RequestParam(value = "type") List<Long> types,
			@RequestParam(value = "is_refuse") int isRefuse, @RequestParam(value = "page") int page, @RequestParam(value = "rows") int rows)
			throws IOException {
		return JsonResult.ok(bjcmsRepertoryServiceImpl.selectPageInfos(originalFilename, labelids, types, isRefuse, page, rows));
	}

	@PostMapping(value = "/index-update.html")
	@ResponseBody
	public JsonResult update(@RequestBody @Validated RepertoryUpdate repertoryUpdate, BindingResult bindingResult) {
		JsonResult messageError = JsonResult.messageError(bindingResult);
		if (messageError != null) {
			return messageError;
		}
		if (!bjcmsRepertoryServiceImpl.update(repertoryUpdate)) {
			return JsonResult.assistance();
		}
		return JsonResult.ok(1);
	}

	@PostMapping(value = "/index-delete.html")
	@ResponseBody
	public JsonResult delete(@RequestParam("id") int id) {
		JcmsRepertory repertory = bjcmsRepertoryServiceImpl.getById(id);
		if (repertory == null) {
			return JsonResult.illegal();
		}
		repertory.setRefuse(1);
		boolean saveOrUpdate = bjcmsRepertoryServiceImpl.saveOrUpdate(repertory);
		if (!saveOrUpdate) {
			return JsonResult.assistance();
		}
		return JsonResult.ok(1);
	}

	@PostMapping(value = "/outsidelink-save.html")
	@ResponseBody
	public JsonResult outsidelinkSave(@RequestBody @Validated RepertoryOutsidelinkSave repertoryOutsidelink, BindingResult bindingResult) {
		JsonResult messageError = JsonResult.messageError(bindingResult);
		if (messageError != null) {
			return messageError;
		}
		if (!bjcmsRepertoryServiceImpl.saveOutsideLink(repertoryOutsidelink)) {
			return JsonResult.assistance();
		}
		return JsonResult.messageSuccess(1);
	}

	@GetMapping(value = "/label.html")
	public ModelAndView label(ModelAndView model) throws IOException {
		model.setViewName("backend/repertory/label");
		return model;
	}

	@GetMapping(value = "/label-infos.html")
	@ResponseBody
	public JsonResult labelInfos(@RequestParam(value = "page") int page, @RequestParam(value = "rows") int rows) throws IOException {
		Page<JcmsRepertoryLabel> labelInfos = bjcmsRepertoryLabelServiceImpl.labelInfos(page, rows);
		return JsonResult.ok(PageDataUtil.easyuiResult(labelInfos));
	}

	@PostMapping(value = "/label-infos-all.html")
	@ResponseBody
	public JsonResult labelInfo() {
		List<JcmsRepertoryLabel> list = bjcmsRepertoryLabelServiceImpl.list();
		return JsonResult.ok(PageDataUtil.easyuiResult(list));
	}

	@PostMapping(value = "/label-save.html")
	@ResponseBody
	public JsonResult labelSave(@RequestParam(value = "id", defaultValue = "0") Long id, @RequestParam(value = "name") String name) throws IOException {
		if (StrUtil.isBlank(name)) {
			return JsonResult.illegal();
		}
		JcmsRepertoryLabel repertoryLabel;
		if (id == null || id.longValue() < 1) {
			repertoryLabel = new JcmsRepertoryLabel();
		} else {
			repertoryLabel = bjcmsRepertoryLabelServiceImpl.getById(id);
			if (repertoryLabel == null) {
				return JsonResult.illegal();
			}
		}
		repertoryLabel.setName(name);
		if (!bjcmsRepertoryLabelServiceImpl.saveOrUpdate(repertoryLabel)) {
			return JsonResult.assistance();
		}
		return JsonResult.messageSuccess("保存成功！", 1);
	}

	// 标签删除
	@PostMapping(value = "/label-delete.html")
	@ResponseBody
	@Transactional
	public JsonResult labelDelete(@RequestParam(value = "id") long id) throws IOException {
		JcmsRepertoryLabel repertoryLabel = bjcmsRepertoryLabelServiceImpl.getById(id);
		if (repertoryLabel == null) {
			return JsonResult.illegal();
		}

		boolean remove = bjcmsRepertoryLabelServiceImpl.removeById(id);
		if (!remove) {
			return JsonResult.assistance();
		}
		LambdaUpdateWrapper<JcmsRepertory> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
		lambdaUpdateWrapper.eq(JcmsRepertory::getLabelId, id).set(JcmsRepertory::getLabelId, 0);
		boolean update = bjcmsRepertoryServiceImpl.update(lambdaUpdateWrapper);
		if (!update) {
			throw new RuntimeException("更新 Repertory::getLabelId 时失败!");
		}
		return JsonResult.ok(1);
	}

	// 资源回收站
	@GetMapping(value = "/recycle.html")
	public String recycle(HttpServletRequest request) throws JsonProcessingException {
		List<JcmsRepertoryLabel> list = bjcmsRepertoryLabelServiceImpl.list();
		request.setAttribute("labeles", objectMapper.writeValueAsString(PageDataUtil.easyuiResult(list)));
		return "backend/repertory/recycle";
	}

	// 还原资源
	@PostMapping(value = "/recycle-restore.html")
	@ResponseBody
	public JsonResult recycleRestore(@RequestParam("id") long id) throws IOException {
		JcmsRepertory repertory = bjcmsRepertoryServiceImpl.getById(id);
		if (repertory == null) {
			return JsonResult.illegal();
		}
		repertory.setRefuse(0);
		boolean saveOrUpdate = bjcmsRepertoryServiceImpl.saveOrUpdate(repertory);
		if (!saveOrUpdate) {
			return JsonResult.assistance();
		}
		return JsonResult.ok(1);
	}

	// 清除资源
	@PostMapping(value = "/recycle-clear.html")
	@ResponseBody
	@Transactional
	public JsonResult recycleClear(@RequestParam("id") long id) throws IOException {
		JcmsRepertory repertory = bjcmsRepertoryServiceImpl.getById(id);
		if (repertory == null) {
			return JsonResult.illegal();
		}
		boolean removeById = bjcmsRepertoryServiceImpl.removeById(repertory.getId());
		if (!removeById) {
			return JsonResult.assistance();
		}

		// 外链接直接返回结果
		if (repertory.getType().intValue() == RepertoryUtil.OUTSIDELINK) {
			return JsonResult.ok(1);
		}

		// 物理删除文件
		String repertoryFullPathByPath = repertoryUtil.getRepertoryFullPathByPath(repertory.getFilepath());
		File file = new File(repertoryFullPathByPath);
		if (file.isFile() && !file.delete()) {
			throw new RuntimeException("删除文件出错！");
		}
		return JsonResult.ok(1);
	}

}
